﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Loader;
using System.Text;
using System.Threading.Tasks;

namespace ServerCommon.Architecture
{
    public class ExitSignal
    {
        private bool _exit;

        public event EventHandler? Exit;

        private static ExitSignal? _instance = null;
        public static ExitSignal Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new ExitSignal();
                }
                return _instance;
            }
        }

        public ExitSignal()
        {
            _exit = false;

            Console.CancelKeyPress += (o, e) =>
            {
                e.Cancel = true;
                callExit();
            };

            AssemblyLoadContext.Default.Unloading += (p) =>
            {
                callExit();
            };

            AppDomain.CurrentDomain.ProcessExit += (o, e) =>
            {
                callExit();
            };
        }

        private void callExit()
        {
            if (Exit == null || _exit)
            {
                return;
            }

            Exit(this, EventArgs.Empty);
            _exit = true;
            System.Threading.Thread.Sleep(10000);
        }
    }
}
